package com.mingqijia.gassafety.webserver.service.cmp.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mingqijia.gassafety.db.entity.DeviceState;
import com.mingqijia.gassafety.db.entity.Dtu;
import com.mingqijia.gassafety.db.entity.DtuAep;
import com.mingqijia.gassafety.db.entity.RecordController;
import com.mingqijia.gassafety.db.mapper.DeviceStateMapper;
import com.mingqijia.gassafety.db.mapper.DtuAepMapper;
import com.mingqijia.gassafety.db.mapper.DtuMapper;
import com.mingqijia.gassafety.db.mapper.RecordControllerMapper;
import com.mingqijia.gassafety.webserver.request.cmp.notify.RegistrationRequest;
import com.mingqijia.gassafety.webserver.service.ConsumerLocationService;
import com.mingqijia.gassafety.webserver.service.cmp.CmpRegistrationService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import static com.mingqijia.gassafety.webserver.constant.DeviceConstant.CONTROLLER_STATUS_0;

/**
 * Description:
 *
 * @author zhufeng
 * @since 2022/8/10
 */
@Service
@Slf4j
public class CmpRegistrationServiceImpl implements CmpRegistrationService {
    public static final String format = "yyyy-MM-dd HH:mm:ss";
    @Resource
    private DtuMapper dtuMapper;

    @Resource
    private DtuAepMapper dtuAepMapper;
    @Resource
    private RecordControllerMapper recordControllerMapper;

    @Resource
    private DeviceStateMapper deviceStateMapper;
    
    @Autowired
    ConsumerLocationService consumerLocationService;

    /**
     * 注册激活
     *
     * @param request
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject registration(RegistrationRequest request) {
        JSONObject res = new JSONObject();
        try {
            Dtu dtu = dtuMapper.selectByImei(request.getImei(), "");
            log.info("registration-dtu:{}",JSONObject.toJSONString(dtu));
            if (dtu != null) {
                res.put("deviceCode", dtu.getDeviceCode());
                res.put("regStatus", 0);
                //DtuAep dtuAep = dtuAepMapper.selectCmpByImei(request.getImei(), dtu.getSpId());
                QueryWrapper<DtuAep> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().or().eq(DtuAep::getIMEI, request.getImei()).eq(DtuAep::getSpId, dtu.getSpId())
                        .eq(DtuAep::getIsDeleted, 0).ne(DtuAep::getActivateStatus, 1);
                List<DtuAep> dtuAepList = dtuAepMapper.selectList(queryWrapper);
                log.info("registration-dtuAep:{}",JSONObject.toJSONString(dtuAepList));
                //if (dtuAep == null || dtuAep.getActivateStatus() == 1) return res;
                if (CollectionUtils.isEmpty(dtuAepList)) {
                    return res;
                }
                String resultDesc = request.getResultDesc();
                if (!StringUtils.isEmpty(resultDesc)){
                    log.error("激活失败：",resultDesc);
                    return res;
                }
                for (DtuAep dtuAep : dtuAepList) {
                    dtuAep.setActivateStatus(request.getActivationResult()==0?1:0);
                    dtuAep.setActivateTime(request.getActivationTime());
                    dtuAepMapper.updateById(dtuAep);
                }
                RecordController recordController = new RecordController();
                recordController.setDeviceId(dtu.getId());
                recordController.setConsumerId(dtu.getConsumerId());
                recordController.setRecordType(request.getRecordType());
                recordController.setControllerStatus(CONTROLLER_STATUS_0);
                recordController.setValveTriggered(9);
                recordController.setPowerModel(request.getPowerMode());
                recordController.setMainBatteryValue(request.getElectricQuantity());
                recordController.setSingal(request.getSignal());
                recordController.setSpId(dtu.getSpId());
                recordControllerMapper.insert(recordController);
                dtu.setModuleModel(request.getModuleModel());
                dtu.setControllerType(request.getControlType());
                dtu.setAppSite(request.getAppSite());
                dtu.setPowerModel(request.getPowerMode());
                log.info("registration-expirationTime:{},{},{}",DateUtil
                        .offsetMonth(DateUtil.parse(request.getActivationTime()), dtu.getValidity() * 12).toString(format));
                dtu.setExpirationTime(DateUtil
                        .offsetMonth(DateUtil.parse(request.getActivationTime()), dtu.getValidity() * 12).toString(format));
                log.info("registration-insert:{},{},{}",JSONObject.toJSONString(dtu)
                        ,JSONObject.toJSONString(recordController),JSONObject.toJSONString(dtuAepList));
                dtuMapper.updateById(dtu);
                DeviceState device = deviceStateMapper.selectByDeviceId(dtu.getId(), dtu.getSpId());
                if (device != null) {
                    device.setDeviceStatus(1);
                    device.setDeviceId(dtu.getId());
                    device.setSignal(request.getSignal());
                    device.setMainBatteryValue(request.getElectricQuantity());
                    deviceStateMapper.updateById(device);
                } else {
                    DeviceState deviceState = new DeviceState();
                    deviceState.setDeviceStatus(1);
                    deviceState.setDeviceId(dtu.getId());
                    deviceState.setSignal(request.getSignal());
                    deviceState.setMainBatteryValue(request.getElectricQuantity());
                    deviceStateMapper.insert(deviceState);
                }
                
                consumerLocationService.updateConsumerLocationDeviceNum(dtu.getSpId(), dtu.getConsumerId());
                
                res.put("regStatus", 1);
            }
        } catch (Exception e) {
            log.error("registration-error:{}",e);
        }
        return res;
    }
}
